package com.example.mygif;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.mygif.databinding.ActivityMainBinding;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yanzhenjie.permission.runtime.PermissionDef;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static boolean DEBUG = true;
    private static final String TAG = "MainActivity";
    private static final int REQUEST_CODE_SETTING = 1;

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    private GifHandler mGifHandler;
    private ActivityMainBinding mBinding;
    private Bitmap mBitmap;
    private final long DELAY = 100;
    private final Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {

            try {
                int delay = mGifHandler.drawFrame(mBitmap);
                mHandler.sendEmptyMessageDelayed(1, delay);
                mBinding.image.setImageBitmap(mBitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        requestPermission(Permission.WRITE_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE);
        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }

    /**
     * Request permissions.
     */
    private void requestPermission(@PermissionDef String... permissions) {
        AndPermission.with(this)
                .runtime()
                .permission(permissions)
                .rationale(new RuntimeRationale())
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Toast.makeText(MainActivity.this, "申请成功", Toast.LENGTH_SHORT).show();
                        if (null == mGifHandler) {
                            mGifHandler = new GifHandler();
                        }
                    }
                })
                .onDenied(permissions1 -> {
                    Toast.makeText(MainActivity.this, "申请失败", Toast.LENGTH_SHORT).show();
                    if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, permissions1)) {
                        showSettingDialog(MainActivity.this, permissions1);
                    }
                })
                .start();
    }

    /**
     * Display setting dialog.
     */
    public void showSettingDialog(Context context, final List<String> permissions) {
        List<String> permissionNames = Permission.transformText(context, permissions);
        String message = context.getString(R.string.message_permission_always_failed,
                TextUtils.join("\n", permissionNames));

        new AlertDialog.Builder(context).setCancelable(false)
                .setTitle(R.string.title_dialog)
                .setMessage(message)
                .setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPermission();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }

    /**
     * Set permissions.
     */
    private void setPermission() {
        AndPermission.with(this).runtime().setting().start(REQUEST_CODE_SETTING);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SETTING: {
                Toast.makeText(MainActivity.this, R.string.message_setting_comeback, Toast.LENGTH_SHORT).show();
                break;
            }
            default:
                break;
        }
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    public void loadGif(View view) {
        if (null != mGifHandler) {
            File file = new File(Environment.getExternalStorageDirectory(), "fire.gif");
            mGifHandler.loadFile(file.getAbsolutePath());

            try {
                int with = mGifHandler.getWith();
                int height = mGifHandler.getHeight();
                if (DEBUG) {
                    Log.i(TAG, "with == " + with);
                    Log.i(TAG, "height == " + height);
                }
                mBitmap = Bitmap.createBitmap(with, height, Bitmap.Config.ARGB_8888);
                int delay = mGifHandler.drawFrame(mBitmap);
                mBinding.image.setImageBitmap(mBitmap);
                mHandler.sendEmptyMessageDelayed(1, delay);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {

            try {
                throw new Exception("mGifHandler is null");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void test(View view) {
        GifHandler gifHandler = new GifHandler();
        gifHandler.test();
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    public void testBitmap(View view) {

        Bitmap bitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
        mGifHandler.testBitmap(bitmap);
        mBinding.imgBitmap.setImageBitmap(bitmap);
    }
}